package main

import (
	"fmt"
	"github.com/frankrap/huobi-api/hbdm"
	"github.com/markcheno/go-talib"
	"log"
)

func (this *Trade) Macd(fives []float64) {
	difs, deas, macds := talib.Macd(this.ClosePrices, 12, 26, 9)
	// unstable := 100 // 前 100 条数据不稳定 不可做参考
	l := len(macds)
	fmt.Println(macds[l-11 : l-1])
	currentMACD := macds[l-1:][0]
	log.Println("[当前5分钟MACD指标]: ", currentMACD, " DIF: ", difs[len(difs)-1], "DEA: ", deas[len(deas)-1])
	// 判断是否有金叉
	if difs[len(difs)-1] >= deas[len(deas)-1] &&
		difs[len(difs)-2] < deas[len(deas)-2] &&
		difs[len(difs)-3] < deas[len(deas)-3] &&
		difs[len(difs)-4] < deas[len(deas)-4] {
		this.RecommendDirection = 0
		this.RecommendBuyPrice = fives[0]
		if this.RecommendBuyPrice > this.ClosePrices[0] {
			this.RecommendBuyPrice = this.ClosePrices[0]
		}
		this.NeedForceSell = true
		log.Println("[出现金叉]", this.CurrentPrice)
	}
	// 判断是否有死叉
	if difs[len(difs)-1] <= deas[len(deas)-1] &&
		difs[len(difs)-2] > deas[len(deas)-2] &&
		difs[len(difs)-3] > deas[len(deas)-3] &&
		difs[len(difs)-4] > deas[len(deas)-4] {
		this.RecommendDirection = 1
		this.NeedForceBuy = true
		this.RecommendSellPrice = fives[0]
		if this.RecommendSellPrice < this.ClosePrices[0] {
			this.RecommendSellPrice = this.ClosePrices[0]
		}
		log.Println("[出现死叉]", this.CurrentPrice)
	}
}

func (this *Trade) HourMacd() {
	difs, deas, macds := talib.Macd(this.HourClosePrices, 12, 26, 9)
	// unstable := 100 // 前 100 条数据不稳定 不可做参考
	l := len(macds)
	currentMACD := macds[l-1:][0]
	log.Println("[小时MACD]当前 MACD: ", currentMACD, " DIF: ", difs[len(difs)-1], "DEA: ", deas[len(deas)-1])
	if this.RecommendDirection == 1 && currentMACD > 0 && macds[l-1] > 0 && macds[l-1] > macds[l-2] {
		log.Println("[当前空单取消] 小时线看多")
		this.RecommendDirection = -1

	}
	if this.RecommendDirection == 0 && currentMACD < 0 && macds[l-1] < 0 && macds[l-1] < macds[l-2] {
		// 表示 当前适合多单 上一轮 是多 这一轮卖单在增多
		this.RecommendDirection = -1
		log.Println("[当前多单取消] 小时线看空")
	}
}

func (this *Trade) MacdClose(data []hbdm.SwapKLine) (bool, bool) {
	l := len(data)
	fives, _ := this.GetAverages(data)
	// 简单kline 平均线
	cPrices := make([]float64, 0)
	current := data[l-1]
	// 重置
	for i := l - 1; i >= 0; i-- {
		// 将15分钟 k线放入
		cPrices = append(cPrices, data[i].Close)
	}
	_, _, macds := talib.Macd(cPrices, 12, 26, 9)
	// unstable := 100 // 前 100 条数据不稳定 不可做参考
	l = len(macds)
	canCloseBuy := false
	canCloseSell := false
	if macds[l-1] > macds[l-2] && current.Close > fives[0] {
		// 平空
		canCloseSell = true
	}
	if macds[l-1] >= macds[l-2] && current.Close < fives[0] {
		// 平多
		canCloseBuy = true
	}
	if !canCloseBuy && !canCloseSell {
		if this.BuyPosition.ProfitUnreal >= 1 {
			canCloseBuy = true
		}
		if this.SellPosition.ProfitUnreal >= 1 {
			canCloseSell = true
		}
	}
	return canCloseBuy, canCloseSell
}
